<template>
  <div v-loading="isLoading" class="comp-tree">
    <div
      class="addNew"
      @click="handleAddTop"
      @mouseover="yr"
      @mouseleave="yc"
      :style="active"
    >
      <img :src="addImg" alt="" style="width: 20px; height: 20px" />
      <span style="padding: 0 0 1px 5px">添加分组 </span>
    </div>

    <!-- tree -->
    <el-tree
      ref="SlotTree"
      :data="pageOptions"
      :props="defaultProps"
      :expand-on-click-node="false"
      highlight-current
      :node-key="NODE_KEY"
      @node-click="nodeClick"
      :default-expand-all="true"
      :current-node-key="pageOptions[0].children[0].id"
    >
      <div class="comp-tr-node" slot-scope="{ node, data }">
        <!-- 编辑状态 -->
        <template v-if="node.isEdit">
          <el-input
            v-model="data.name"
            autofocus
            size="mini"
            :ref="'slotTreeInput' + data[NODE_KEY]"
            @blur.stop="handleInput(node, data)"
            @keyup.enter.native="handleInput(node, data)"
          ></el-input>
        </template>

        <!-- 非编辑状态 -->
        <template v-else>
          <!-- 名称： 新增节点增加class（is-new） -->
          <span
            :class="[
              data[NODE_KEY] < NODE_ID_START ? 'is-new' : '',
              'comp-tr-node--name',
            ]"
          >
            {{ node.label }}
          </span>

          <!-- 按钮 -->
          <span class="comp-tr-node--btns">
            <!-- 新增 -->
            <el-button
              icon="el-icon-plus"
              size="mini"
              circle
              type="primary"
              @click.stop="handleAdd(node, data)"
            ></el-button>
            <!-- 编辑 -->
            <el-button
              icon="el-icon-edit"
              size="mini"
              circle
              type="info"
              @click.stop="handleEdit(node, data)"
            ></el-button>
            <!-- 复制 -->
              <el-button v-if="node.level!=1"
              icon="el-icon-copy-document"
              size="mini"
              circle
              type="info"
              @click.stop="handleCopy(node, data)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              icon="el-icon-delete"
              size="mini"
              circle
              type="danger"
              @click.stop="handleDelete(node, data)"
            ></el-button>
          </span>
        </template>
      </div>
    </el-tree>
  </div>
</template>

<script>
import addImg from "@/assets/images/addPageMenu.png";
import addPageMenu from "@/assets/images/addPageMenu.png";
import addPageMenu1 from "@/assets/images/addPageMenu1.png";
import { pageOptions } from "./mobileConfig.js";
export default {
  name: "component-tree",
  data() {
    return {
      addImg,
      addPageMenu1,
      addPageMenu,
      active: "",
      isLoading: false, // 是否加载
      setTree: [], // tree数据
      NODE_KEY: "id", // id对应字段
      MAX_LEVEL: 2, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: "children",
        label: "name",
      },
      initParam: {
        // 新增参数
        name: "新建页面",
        parentId: 0,
        children: [],
        fields: [],
      },
    };
  },
  props: {
    pageOptions: {
      type: Array,
      default: function () {
        return [];
      },
      required: true,
    },
  },
  watch: {},
  created() {
    // 初始值
    this.setTree = this.pageOptions;
    this.startId = this.NODE_ID_START;
  },
  methods: {
    // 节点被点击时的回调
    nodeClick(data, node, item) {
      if (node.level === 2) {
        this.$emit("activePage", data.fields, data.name);
      }
    },
    //鼠标移入
    yr() {
      this.active = "color:#1890ff";
      this.addImg = this.addPageMenu1;
    },
    //鼠标移出
    yc() {
      this.active = "";
      this.addImg = this.addPageMenu;
    },
    handleDelete(_node, _data) {
      // 删除节点
      // console.log(_node, _data);
      // 判断是否存在子节点
      let pageOptionsCopy = [];
      this.pageOptions.forEach((item) => {
        if (Array.isArray(item.children)) {
          pageOptionsCopy.push(...item.children);
        }
      });
      if (_data.children && _data.children.length !== 0) {
        this.$message.error("此节点有子级，不可删除！");
        return false;
      } else if (pageOptionsCopy.length === 1 && _node.level === 2) {
        this.$message.warning("至少保留一个页面");
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              if (_node.level === 2) {
                let curid = pageOptionsCopy.findIndex((v) => {
                  return v.id === _data.id;
                });
                curid = !curid ? curid + 1 : curid - 1;
                this.$refs.SlotTree.setCurrentKey(pageOptionsCopy[curid].id);
                this.$emit(
                  "activePage",
                  pageOptionsCopy[curid].fields,
                  pageOptionsCopy[curid].name
                );
              }
              this.$refs.SlotTree.remove(_data);
              this.$message.success("删除成功！");
              console.log(this.pageOptions, "删除");
              this.setPage();
            }
          });
        };
        // 二次确认
        let ConfirmFun = () => {
          this.$confirm("是否删除此节点？", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              DeletOprate();
            })
            .catch(() => {});
        };
        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START
          ? DeletOprate()
          : ConfirmFun();
      }
    },
    handleInput(_node, _data) {
      // 修改节点
      // console.log(_node, _data);
      // 退出编辑状态
      console.log(this.pageOptions, "pageOptions");
      this.setPage();
      if (_node.isEdit) {
        this.$set(_node, "isEdit", false);
      }
    },
    handleEdit(_node, _data) {
      // 编辑节点
      // console.log(_node, _data);
      // 设置编辑状态
      if (!_node.isEdit) {
        this.$set(_node, "isEdit", true);
      }
      // 输入框聚焦
      this.$nextTick(() => {
        if (this.$refs["slotTreeInput" + _data[this.NODE_KEY]]) {
          this.$refs[
            "slotTreeInput" + _data[this.NODE_KEY]
          ].$refs.input.focus();
        }
      });
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data);
      // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning("当前已达到" + this.MAX_LEVEL + "级，无法新增！");
        return false;
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)); // copy参数
      obj.parentId = _data[this.NODE_KEY]; // 父id
      let len = _data.children.length;
      obj[this.NODE_KEY] = _data.id + "-" + ++len; // 节点id
      // 判断字段是否存在
      if (!_data.children) {
        this.$set(_data, "children", []);
      }
      // 新增数据
      _data.children.push(obj);
      this.setPage();
      // 展开节点
      if (!_node.expanded) {
        _node.expanded = true;
      }
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)); // copy参数
      obj.name = '新建组';
      let len = this.pageOptions.length;
      obj[this.NODE_KEY] = ++len; // 节点id：逐次递减id
      this.pageOptions.push(obj);
      this.setPage();
    },
    handleCopy(_node,_data){
      let nowtime = Date.now();
      let arr = this.pageOptions.find(item=>{
        return item.id===_data.parentId;
      }).children;
      let id = arr.findIndex(item=>{
        return item.id===_data.id;
      });
      let dataCopy = JSON.parse(JSON.stringify(_data));
      dataCopy.id = nowtime;
      dataCopy.name = _data.name+'(复制)';
      dataCopy.fields.forEach((item,index)=>{
        item.i = nowtime + index;
      });
      arr.splice(id+1,0,dataCopy);
      this.setPage();
    },
    setPage(){
      let arr = JSON.parse(JSON.stringify(this.pageOptions));
      this.$store.commit("mobile/SET_PAGESTORE", arr);
    }
  },
};
</script>
<style lang="scss">
/* common */
// 显示按钮
.show-btns {
  opacity: 1;
}
/* common end */
.comp-tree {
  width: 100%;
  max-width: 700px;
  max-height: 80vh;
  // padding: 0.8em;
  overflow: hidden;
  font-size: 14px;
  .addNew {
    padding-bottom: 5px;
    border-bottom: 1px solid rgba(168, 167, 167, 0.3);
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  // 顶部按钮
  .comp-tr-top {
    width: 100px;
    margin-bottom: 2em;
  }
  // 自定义节点
  .comp-tr-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    // label
    .comp-tr-node--name {
      display: inline-block;
      line-height: 40px;
      min-height: 40px;
      // 新增
      &.is-new {
        font-weight: bold;
      }
    }
    // button
    .comp-tr-node--btns {
      opacity: 0;
      transition: opacity 0.1s;
      .el-button {
        transform: scale(0.6); // 缩小按钮
        & + .el-button {
          margin-left: -1px;
        }
      }
    }
  }
  // 高亮显示按钮
  .is-current {
    & > .el-tree-node__content {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
  // 悬浮显示按钮
  .el-tree-node__content {
    &:hover {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
  .el-tree-node__content {
    height: inherit;
  }
}
</style>